(function() {
  var httpRequest;
  window.onload = function() {makeGetRequest('ajax?sub=all');};

  function makeGetRequest(url) {
    httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = writeContents;
    url += '&' + (new Date()).getTime();
    httpRequest.open('GET', url);
    httpRequest.send();
  }

  function toggleArticle(id) {
    var elem = document.getElementById(id);
    if (window.getComputedStyle(elem).display === 'none') {
      elem.style.display = 'block';
    } else {
      elem.style.display = 'none';
    }
  }

  function writeContents() {
    if (httpRequest.readyState === 4 && httpRequest.status === 200) {
      var xmlDoc = httpRequest.responseXML;
      var items = xmlDoc.getElementsByTagName('itemlist')[0];
      if (items) {
        items = items.getElementsByTagName('item');
        var ul = document.createElement('ul');
        for (var i = 0; i < items.length; i++) {
          var li = document.createElement('li');
          var h1 = document.createElement('h1');
          var title = items[i].getElementsByTagName('title')[0].firstChild.
                nodeValue;
          var article = document.createElement('article');
          var desc = items[i].getElementsByTagName('description')[0].
                      firstChild.nodeValue;
          h1.setAttribute('class', 'outertitle');
          h1.onclick = (function(j) {
            var curItemClass = 'art' + j;
            return function() {
              toggleArticle(curItemClass);
            };
          })(i);
          h1.appendChild(document.createTextNode(title));
          li.appendChild(h1);
          var innerH1 = document.createElement('h1');
          innerH1.setAttribute('class', 'innertitle');
          anchor = document.createElement('a');
          anchor.setAttribute('href',
              items[i].getElementsByTagName('link')[0].firstChild.
              nodeValue);
          anchor.appendChild(document.createTextNode(title));
          innerH1.appendChild(anchor);
          article.appendChild(innerH1);
          article.innerHTML += desc;
          article.setAttribute('id', 'art' + i);
          li.appendChild(article);
          ul.appendChild(li);
        }
        var htmlItems = document.getElementById('items');
        htmlItems.innerHTML = '';
        htmlItems.appendChild(ul);

        //write 'Next' link
        items = xmlDoc.getElementsByTagName('itemlist')[0];
        var curs = items.getAttribute('more');
        if (curs === 'True') {
          curs = items.getAttribute('cursor')
          nextLink = document.createElement('a');
          nextLink.setAttribute('href', '#');
          nextLink.appendChild(document.createTextNode('Next'));
          var url = 'ajax?sub=all&cursor=' + curs;
          nextLink.onclick = function() {makeGetRequest(url);}
          htmlItems.appendChild(nextLink);
        }
      }
    }
  }
})();
